#include "chat.h"

void* share_memory;

int main(int argc, char** argv){
    char name[20];
    int opt;
    while((opt = getopt(argc, argv, "n:")) != -1){
        switch(opt){
            case 'n':
                strcpy(name, optarg);
                break;
            default:
                fprintf(stderr, "Usage: %s -n name\n", argv[0]);
                exit(1);
        }
    }

    //printf("parse complete\n");
    key_t key = ftok(".", 20210106);
    int shmid;
    if((shmid = shmget(key, sizeof(struct Msg), IPC_CREAT | 0666)) < 0){
        perror("shmget");
        exit(1);
    }

    if((share_memory = shmat(shmid, NULL, 0)) == (void*)-1){
        perror("shmat");
        exit(1);
    }
    //printf("build memory complete\n");

    struct Msg* message = (struct Msg*)share_memory;
    //printf("%s\n", message->name);
    char temp[1024];

    while(1){
        printf("in while...\n");
        scanf("%[^\n]s", temp);
        getchar();
        if(!strlen(temp)){
            continue;
        }

        while(1){
            if(!strlen(message->msg)){
                pthread_mutex_lock(&message->mutex);
                break;
            }
        }
        printf("in lock...\n");
        strcpy(message->name, name);
        strcpy(message->msg, temp);
        pthread_cond_signal(&message->cond);
        pthread_mutex_unlock(&message->mutex);
    }
    return 0;
}